#include "myUdp_Client.hpp"

static string default_severIp = "127.0.0.1";
static uint16_t default_severPort = 8888;

void Usage()
{
    printf("Uages:\n\tPlease enter:./myUdp_Client ip port\n");
    printf("            or enter:./myUdp_Cilent\n");
}

int main(int arg, char *args[])
{
    if (arg > 3)
    {
        Usage();
        exit(USAGE_ERR);
    }
    // std::cout<<"This is Client!"<<std::endl;

    string severIp;
    uint16_t severPort;
    if (arg == 1)
    {
        printf("This is default:severIp:127.0.0.1,severPort=8888\n");
        Usage();
        severIp = default_severIp;
        severPort = default_severPort;
    }
    else if (arg == 2)
    {
        severIp = args[1];
        severPort = default_severPort;
    }
    else
    {
        string severIp = args[1];
        uint16_t severPort = atoi(args[2]);
    }
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cerr << "创建套接字失败！：" << strerror(errno) << endl;
        exit(SOCKET_ERR);
    }
    struct sockaddr_in sever;
    bzero(&sever, sizeof(sever)); // 初始化置0
    sever.sin_addr.s_addr = inet_addr(severIp.c_str());
    sever.sin_port = htons(severPort);
    sever.sin_family = AF_INET;
    char buf[2048] = {0};
    while (1)
    {
        // 发
        string message;

        getline(cin,message);
        cout<<"客户准备发送！"<<endl;
        int sendRet = sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&sever, sizeof(sever));
        if (sendRet < 0)
        {
            cerr << "发送失败！：" << strerror(errno) << endl;
            exit(SEND_ERR);
        }
        // 收
        cout<<"客户发送成功！"<<endl;

        socklen_t len = sizeof(sever);
        int n = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&sever, &len);
        if (n > 0)
        {
            buf[n] = 0;
        }
        else
        {
            cout<<"客户端接受失败！"<<endl;
            continue;
            
        }
        cout <<"结果：\n"<< buf << endl;
    }
    return 0;
}